<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from "element-plus";
import { saveReceipt } from '@/api/receipt/receipt'
import OverAccount from "@/views/receipt/OverAccount.vue";
import ChooseSupplier from "@/views/set/supplier/ChooseSupplier.vue";
import Source from "@/views/receipt/source.vue"
import { getUser } from "@/utils/session.js";
import host from '@/utils/env.js'
//表格数据
const tableData = ref([])

//初始化10行
function init() {
  for (let i = 1; i <= 4; i++) {
    addRow()
  }
}

function addRow() {
  tableData.value.push({
    account:"",
    pay:0,
    payway:"",
    accountNum:"",
    certificate:"",
    note:"",
    show: {}
  })
}

//单元格双击事件
const lastRow = ref({})//记录上一次双击的是哪一行
function cellck(row, column) {
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
  let tmp = column.property;
  row.show[tmp] = true;
  //记录双击的行
  lastRow.value = row;
}

//删除行
const receiptRef = ref(null)//表格引用
function delRow() {
  let rows = receiptRef.value.getSelectionRows()
  if (rows.length == 0) {
    ElMessage({
      message: "请选择要删除的行！",
      type: "warning"
    });
  }
  rows.forEach(r => {
    removeData(r)
  })
}

//从tableData移除行，r代表要移除的行
function removeData(r) {
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //获取当前行对象
    let tmp = tableData.value[i];
    //判断tmp是否是要删除的对象r
    if (tmp == r) {
      tableData.value.splice(i, 1);
      break;//中止循环
    }
  }
}

//付款单
const receiptForm = ref({
  supplierId: 0,
  supplierName: "",
  billDate: "",
  note:"",
  auditUser:"",
  user:getUser().username,
  sourceCode:"",
  eid:getUser().eid,
  type:1,
  money:0
})
//新增保存
async function save() {
  tableData.value.forEach(el => {
    receiptForm.value.money += el.pay;
  })
  let detail = [];//保存用户填写的明细
  //便利表格数据
  tableData.value.forEach(r => {
    //判断当前对象中是否选择了商品 如果是，加入到明细
    if (r.account != undefined && r.account != "") {
      detail.push(r)
    }
  })
  if (detail.length == 0) {
    ElMessage({
      message: "采购明细不能为空!",
      type: "warning"
    })
    return
  }
  //参数值
  let data = receiptForm.value;//付款单基本信息
  //将明细加入采购单
  data.receiptDetailList = detail;
  //保存
  let res = await saveReceipt(data);
  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    })
  }
}
//商品选择
const isshowchoose = ref(false);//是否显示商品选择框
//选择商品
function choose(rows) {
  if (rows.length == 0) {
    return
  }
  //获取选择行的索引
  let index = -1;
  //遍历表格数据，查询选择的第一个对象的未知
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    //临时对象
    let tmp = tableData.value[i];
    if (tmp == lastRow.value) {
      index = i;
      break;
    }
  }
  if (index == -1)
    return;
  //遍历选择的明细
  for (let i = 0, len = rows.length; i < len; i++) {
    //临时对象
    let obj = tableData.value[index];
    obj.goodsId=rows[i].id;
    obj.account=rows[i].name;
    obj.payway=rows[i].type;
    obj.unit=rows[i].unit;
    obj.warehouse=rows[i].warehouseName;
    obj.wid=rows[i].warehouseId;
    index++;
  }
  //先清空之前添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
}
//供应商选择
const isshowsupplier = ref(false);//是否显示选择供应商
//选择供应商
function chg(row) {
  console.log(row)
  receiptForm.value.supplierId=row.id;
  receiptForm.value.supplierName=row.name;
}
//合同上传
let tmp = {};
const fileList = ref([])
function handleChange(res) {
  //获取接口返回数据
  if (res.code == 200) {
    ElMessage({
      message: "上传成功,可点击查看!",
      type: "success"
    })
    //上传成功获取上传后的路径和附件名称
    tmp.path = res.data;

    console.log(tmp)
  }
}
function shib() {
  ElMessage({
    message: '上传失败，文件大小异常！',
    type: 'warning',
  })
}

//选择采购单
const isshowsource = ref(false)
function sou(row) {
  receiptForm.value.sourceCode=row.code;
  receiptForm.value.auditUser=row.auditor;
}
let user = {}
//-----------生命周期-----------
onMounted(() => {
  init()
  user = getUser()
  console.log(user)
})
</script>

<template>
  <div class="root">
    <!--工具条-->
    <div class="toolbar">
      <el-button type="primary" size="small">保存并新增</el-button>
      <el-button type="primary" size="small" @click="save">保存</el-button>
    </div>
    <!--第一行 -->
    <el-row style="margin-top: 20px">
      <el-col :span="8" style="margin-left: 20px;">
        收款方:<input type="text" @click="isshowsupplier = true" placeholder="请选择收款方" class="ipt"
          v-model="receiptForm.supplierName" />
      </el-col>
      <el-col :span="8">
        单据日期:
        <el-date-picker type="date" placeholder="请选择" value-format="YYYY-MM-DD" size="small"
          v-model="receiptForm.billDate" />
      </el-col>
      <el-col :span="6"> 单据编号：FKDJ20240507100023</el-col>
    </el-row>

    <div class="detail">
      <!--明细-->
      <div class="detail-title">
        <span>付款单明细</span>
        <el-button type="primary" size="small" @click="addRow">增行</el-button>
        <el-button type="primary" size="small" @click="delRow">删行</el-button>
      </div>
      <!--列表-->
      <el-table :data="tableData" style="width: 100%" stripe border @cell-click="cellck" ref="receiptRef">
        <el-table-column type="selection" width="50" header-algin="center" align="center" />
        <el-table-column type="index" label="序号" width="80" header-algin="center" align="center" />

        <el-table-column prop="account" label="结算账户" header-algin="center" align="center" width="200">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{ row.account }}</span>
            <el-input v-else v-model="row.account" placeholder="点击选择结算账户" @click="isshowchoose = true"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="pay" label="付款金额" width="150" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
                row.pay
              }}</span>
            <el-input-number v-else v-model="row.pay" size="small" :min="0" :precision="2"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="payway" label="结算方式" width="120" header-algin="center" align="center">
          <template v-slot="{row}">
            <span v-if="row.payway==1">现金</span>
            <span v-else-if="row.payway==2">银行卡</span>
          </template>
        </el-table-column>

        <el-table-column prop="accountNum" label="结算号" width="200" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
                row.accountNum
              }}</span>
            <el-input v-else v-model="row.accountNum"/>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="上传凭证" width="140" header-algin="center" align="center">
          <el-upload v-model:file-list="fileList" :action="host + '/upload'" :on-success="handleChange"
                      :on-error="shib" style="width: 80px" :show-file-list="false">
            <el-button type="primary" size="small" style="margin-right: 10px">上传</el-button>
          </el-upload>
          <el-button type="primary" size="small" style="float: right;margin-top: -24px">查看</el-button>
        </el-table-column>
        <el-table-column prop="note" label="备注" header-algin="center" align="center">
          <template v-slot="{ row, column }">
            <span v-if="row.show[column.property] == undefined">{{
                row.note
              }}</span>
            <el-input v-else v-model="row.note"/>
          </template>
        </el-table-column>
      </el-table>
      <!-- 来源单号 -->
      <div style="margin-top: 20px;width: 100%;">
        源单:
        {{receiptForm.sourceCode}}
        <el-button type="primary" size="small" @click="isshowsource = true" v-model="receiptForm.sourceCode">选择</el-button>
      </div>
      <!--   备注信息   -->
      <div>
        <input type="text" placeholder="填写订单备注信息" class="note" v-model="receiptForm.note" />
      </div>
    </div>
    <!--  制单人  -->
    <el-row style="margin: 20px 10px">
      <el-col :span="6">制单人: &nbsp;&nbsp;<span>{{receiptForm.user}}</span></el-col>
      <el-col :span="18">&nbsp;</el-col>
    </el-row>
    <!--  选择商品  -->
    <OverAccount :visible="isshowchoose" @choose="choose" @close="isshowchoose = false"></OverAccount>
    <!--  选择供应商  -->
    <ChooseSupplier :visible="isshowsupplier" @close="isshowsupplier = false" @choose="chg"></ChooseSupplier>
    <!--  选择采购单  -->
    <Source :visible="isshowsource" @choose="sou" @close="isshowsource = false"></Source>
  </div>
</template>

<style scoped>
.root {
  border: #ebeef5 solid 1px;
  background-color: #fff;
  height: 100%;
  padding-left: 20px;
}

.toolbar {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
}

.ipt {
  width: 200px;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
  padding-left: 10px;
}

.detail {
  margin-right: 20px;
  margin-top: 30px;
  padding-left: 10px;
}

.detail-title {
  height: 40px;
  line-height: 40px;
  border: #ebeef5 solid 1px;
  border-bottom-style: none;
  padding-left: 10px;
}

.detail-title button {
  margin-left: 10px;
}

.note {
  width: 100%;
  border-style: none;
  outline-style: none;
  border-bottom: #ebeef5 solid 1px;
  margin-top: 20px;
}
</style>
